<template>
  <div class="receipt-container">
    <!-- 顶部信息栏 - 搜索区域 -->
    <div class="header-card bg-white rounded-lg shadow-md p-6 mb-8">
      <div class="flex flex-col md:flex-row items-center justify-between gap-6">
        <!-- 客户和总欠款 -->
        <div class="flex items-center gap-4">
          <label class="required text-gray-700 font-medium">客户：</label>
          <el-input
            v-model="selectedCustomer.name"
            readonly
            placeholder="点击选择客户"
            @click="customerDialogVisible = true"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 220px"
          />
          <label class="text-gray-700 font-medium">总欠款：</label>
          <el-input
            v-model="totalArrears"
            readonly
            placeholder="0.00"
            style="width: 120px"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
          />
          <label class="required text-gray-700 font-medium">业务员：</label>
          <el-select
            v-model="selectedEmployee"
            placeholder="选择业务员"
            @change="handleEmployeeChange"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 160px"
          >
            <el-option
              v-for="item in employeeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <label class="required text-gray-700 font-medium">单据日期：</label>
          <el-date-picker
            v-model="receiptDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="点击选择日期"
            trigger="click"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 160px"
          />
        </div>

        <!-- 附件 & 单据编号 -->
        <div class="flex items-end gap-4">
          <el-upload
            class="upload-btn"
            :file-list="attachments"
            action="#"
            :on-preview="handlePreview"
          >
            <el-button
              type="text"
              class="text-blue-600 hover:text-blue-800 flex items-center"
            >
              <el-icon><UploadFilled /></el-icon>
              <span class="ml-1">上传附件</span>
            </el-button>
          </el-upload>
          <el-tag class="bg-blue-100 text-blue-800 text-sm">
            {{ receiptNo }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 结算账户表格 -->
    <div class="grid grid-cols-1 gap-8">
      <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold text-gray-800">结算账户</h3>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addSettlementRow"
            class="text-sm px-4"
            >新增行</el-button
          >
        </div>
        <el-table
          :data="settlementTable"
          border
          style="width: 100%"
          stripe
          class="text-sm"
        >
          <!-- 结算账户对话框选择 -->
          <el-table-column label="结算账户" prop="account">
            <template #default="scope">
              <div
                class="cursor-pointer text-blue-600 hover:text-blue-800"
                @click="openAccountDialog(scope.row)"
              >
                {{ getAccountLabel(scope.row.account) || "请选择结算账户" }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="收款金额" prop="amount">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.amount"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 结算方式对话框选择 -->
          <el-table-column label="结算方式" prop="method">
            <template #default="scope">
              <div
                class="cursor-pointer text-blue-600 hover:text-blue-800"
                @click="openMethodDialog(scope.row)"
              >
                {{ getMethodLabel(scope.row.method) || "请选择结算方式" }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="结算号" prop="no">
            <template #default="scope">
              <el-input v-model="scope.row.no" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark">
            <template #default="scope">
              <el-input v-model="scope.row.remark" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="在线交易单号" prop="tradeNo">
            <template #default="scope">
              <el-input v-model="scope.row.tradeNo" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteSettlementRow(scope.row)"
                size="small"
                circle
                hover-effect="light"
              />
            </template>
          </el-table-column>
          <!-- 合计行 -->
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell>{{ settlementTotal }}</el-table-cell>
              <el-table-cell colspan="5"></el-table-cell>
            </el-table-row>
          </template>
        </el-table>
      </div>

      <!-- 预收款源单表格（核心修改部分） -->
      <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold text-gray-800">源单信息</h3>
          <div class="flex gap-2">
            <el-button type="primary" class="text-sm px-4">选择源单</el-button>
            <el-button type="success" class="text-sm px-4">自动核销</el-button>
          </div>
        </div>
        <el-table
          :data="sourceTable"
          border
          style="width: 100%"
          stripe
          class="text-sm"
        >
          <!-- 单据日期 -->
          <el-table-column label="单据日期" prop="docDate">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.docDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 源单编号 -->
          <el-table-column label="源单编号" prop="sourceNo">
            <template #default="scope">
              <el-input v-model="scope.row.sourceNo" size="small" />
            </template>
          </el-table-column>

          <!-- 业务类别 -->
          <el-table-column label="业务类别" prop="businessType">
            <template #default="scope">
              <el-input v-model="scope.row.businessType" size="small" />
            </template>
          </el-table-column>

          <!-- 销售人员 -->
          <el-table-column label="销售人员" prop="seller">
            <template #default="scope">
              <el-input v-model="scope.row.seller" size="small" />
            </template>
          </el-table-column>

          <!-- 客户 -->
          <el-table-column label="客户" prop="customer">
            <template #default="scope">
              <el-input v-model="scope.row.customer" size="small" />
            </template>
          </el-table-column>

          <!-- 订单金额 -->
          <el-table-column label="订单金额" prop="orderAmount">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.orderAmount"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 累计预收金额 -->
          <el-table-column label="累计预收金额" prop="totalPreReceive">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.totalPreReceive"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- *本次预收金额（必填） -->
          <el-table-column label="*本次预收金额" prop="currentPreReceive">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.currentPreReceive"
                type="number"
                size="small"
                required
              />
            </template>
          </el-table-column>

          <!-- 审核状态（下拉） -->
          <el-table-column label="审核状态" prop="auditStatus">
            <template #default="scope">
              <el-select
                v-model="scope.row.auditStatus"
                size="small"
                :options="auditStatusOptions"
                placeholder="请选择"
              />
            </template>
          </el-table-column>

          <!-- 交货日期 -->
          <el-table-column label="交货日期" prop="deliveryDate">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.deliveryDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 关联销货单号 -->
          <el-table-column label="关联销货单号" prop="relatedSalesOrder">
            <template #default="scope">
              <el-input v-model="scope.row.relatedSalesOrder" size="small" />
            </template>
          </el-table-column>

          <!-- 关联购货订单号 -->
          <el-table-column label="关联购货订单号" prop="relatedPurchaseOrder">
            <template #default="scope">
              <el-input v-model="scope.row.relatedPurchaseOrder" size="small" />
            </template>
          </el-table-column>

          <!-- 客户地址 -->
          <el-table-column label="客户地址" prop="customerAddress">
            <template #default="scope">
              <el-input v-model="scope.row.customerAddress" size="small" />
            </template>
          </el-table-column>

          <!-- 单据备注 -->
          <el-table-column label="单据备注" prop="docRemark">
            <template #default="scope">
              <el-input v-model="scope.row.docRemark" size="small" />
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteSourceRow(scope.row)"
                size="small"
                circle
                hover-effect="light"
              />
            </template>
          </el-table-column>

          <!-- 合计行 -->
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell>{{ sourceTotals.totalOrderAmount }}</el-table-cell>
              <el-table-cell>{{
                sourceTotals.totalTotalPreReceive
              }}</el-table-cell>
              <el-table-cell>{{
                sourceTotals.totalCurrentPreReceive
              }}</el-table-cell>
              <el-table-cell colspan="9"></el-table-cell>
              <!-- 适配列数 -->
            </el-table-row>
          </template>
        </el-table>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addSourceRow"
          class="mt-4 text-sm px-4"
          >新增行</el-button
        >
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="mt-8 bg-white rounded-lg shadow-md p-6">
      <div
        class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6"
      >
        <div class="flex flex-col sm:flex-row gap-4">
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">整单折扣：</label>
            <el-input
              v-model.number="discount"
              type="number"
              style="width: 160px"
              size="small"
            />
          </div>
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">本次预收款：</label>
            <el-input
              v-model.number="preReceipt"
              type="number"
              style="width: 160px"
              readonly
              size="small"
            />
          </div>
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
          >
            自定义字段
          </el-button>
        </div>
        <div class="flex justify-end gap-2">
          <el-button type="primary" class="text-sm px-4">保存并新增</el-button>
          <el-button type="success" class="text-sm px-4">保存</el-button>
          <el-button type="info" class="text-sm px-4">审核</el-button>
          <el-button
            type="text"
            class="text-sm text-gray-600 hover:text-gray-800 px-4"
          >
            历史单据
          </el-button>
          <el-button
            type="text"
            class="text-sm text-gray-600 hover:text-gray-800 px-4"
          >
            操作日志
          </el-button>
        </div>
      </div>
    </div>

    <!-- 客户选择弹窗 -->
    <el-dialog
      title="选择客户"
      v-model="customerDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-form :model="customerQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="类别">
          <el-select v-model="customerQuery.category" size="small">
            <el-option label="华中地区" value="central"></el-option>
            <el-option label="华北地区" value="north"></el-option>
            <el-option label="华南地区" value="south"></el-option>
            <el-option label="批发" value="wholesale"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="customerQuery.keyword"
            placeholder="编号/名称/联系人/电话"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="customerQuery.showDisabled" size="small">
            显示禁用客户
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCustomers" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="customerList"
        border
        style="width: 100%"
        @selection-change="handleCustomerSelection"
        stripe
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="类别" prop="category" />
        <el-table-column label="编号" prop="code" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="手机" prop="phone" />
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (customerPageSize = val)"
          @current-change="(val) => (customerPage = val)"
          :current-page="customerPage"
          :page-sizes="[10, 50, 100]"
          :page-size="customerPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="customerTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button type="primary" @click="confirmCustomer" size="small">
            确定
          </el-button>
          <el-button @click="customerDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
          >
            新增客户
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增职员弹窗 -->
    <el-dialog
      title="新增职员"
      v-model="addEmployeeDialogVisible"
      width="400px"
      class="dialog-custom"
    >
      <el-form :model="newEmployee" label-width="80px" class="p-4">
        <el-form-item label="姓名">
          <el-input v-model="newEmployee.name" size="small" />
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="newEmployee.position" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addEmployeeDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button type="primary" @click="saveNewEmployee" size="small">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算账户选择对话框 -->
    <el-dialog
      title="选择结算账户"
      v-model="accountDialogVisible"
      width="400px"
    >
      <div class="p-4">
        <el-input
          v-model="accountSearchKeyword"
          placeholder="搜索结算账户"
          size="small"
          class="mb-4"
        />
        <el-radio-group v-model="selectedAccount">
          <el-radio
            v-for="item in filteredAccountOptions"
            :key="item.value"
            :label="item.value"
            class="block mb-2"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="accountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAccount">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算方式选择对话框 -->
    <el-dialog title="选择结算方式" v-model="methodDialogVisible" width="400px">
      <div class="p-4">
        <el-input
          v-model="methodSearchKeyword"
          placeholder="搜索结算方式"
          size="small"
          class="mb-4"
        />
        <el-radio-group v-model="selectedMethod">
          <el-radio
            v-for="item in filteredMethodOptions"
            :key="item.value"
            :label="item.value"
            class="block mb-2"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="methodDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMethod">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElTag,
  ElPagination,
  ElCheckbox,
  ElUpload,
  UploadFilled,
  ElRadioGroup,
  ElRadio,
} from "element-plus";

// 客户相关
const selectedCustomer = ref({ name: "" });
const customerDialogVisible = ref(false);
const customerQuery = reactive({
  category: "",
  keyword: "",
  showDisabled: false,
});
const customerList = ref([]);
const customerTotal = ref(17); // 模拟数据
const customerPage = ref(1);
const customerPageSize = ref(100);
const totalArrears = ref(0.0);

// 业务员相关
const employeeOptions = ref([
  { label: "(空)", value: "" },
  { label: "老板", value: "boss" },
  { label: "财务-玲", value: "finance-ling" },
  { label: "采购-小陈", value: "purchase-xc" },
  { label: "采购-小王", value: "purchase-xw" },
  { label: "销售-小李", value: "sales-xl" },
  { label: "+新增职员", value: "add" },
]);
const selectedEmployee = ref("");
const addEmployeeDialogVisible = ref(false);
const newEmployee = reactive({ name: "", position: "" });

// 结算下拉选项
const settlementAccountOptions = ref([
  { label: "1001 现金", value: "1001" },
  { label: "1002 银行存款", value: "1002" },
  { label: "1003 微信支付", value: "1003" },
  { label: "1004 支付宝", value: "1004" },
  { label: "1005 其他货币资金", value: "1005" },
  { label: "1122 应收账款", value: "1122" },
  { label: "2202 应付账款", value: "2202" },
  { label: "2203 预收账款", value: "2203" },
  { label: "2204 预付账款", value: "2204" },
]);

const settlementMethodOptions = ref([
  { label: "现金", value: "cash" },
  { label: "支票", value: "check" },
  { label: "汇票", value: "draft" },
  { label: "电汇", value: "telegraphic" },
  { label: "信用证", value: "lc" },
  { label: "微信支付", value: "wechat" },
  { label: "支付宝", value: "alipay" },
  { label: "银行转账", value: "bank" },
  { label: "其他", value: "other" },
]);

// 单据信息
const receiptDate = ref("2025-06-25");
const receiptNo = ref("YSD20250625001"); // 预收款单编号前缀改为YSD
const attachments = ref([]);

// 表格数据
const settlementTable = ref([
  {
    id: 1,
    account: "1002", // 默认选中"银行存款"
    amount: 0,
    method: "bank", // 默认选中"银行转账"
    no: "",
    remark: "",
    tradeNo: "",
  },
]);

// 预收款源单表格数据
const sourceTable = ref([
  {
    id: 1,
    docDate: "", // 单据日期
    sourceNo: "", // 源单编号
    businessType: "", // 业务类别
    seller: "", // 销售人员
    customer: "", // 客户
    orderAmount: 0, // 订单金额
    totalPreReceive: 0, // 累计预收金额
    currentPreReceive: 0, // 本次预收金额（必填）
    auditStatus: "", // 审核状态
    deliveryDate: "", // 交货日期
    relatedSalesOrder: "", // 关联销货单号
    relatedPurchaseOrder: "", // 关联购货订单号
    customerAddress: "", // 客户地址
    docRemark: "", // 单据备注
  },
]);

// 审核状态下拉选项
const auditStatusOptions = ref([
  { label: "草稿", value: "draft" },
  { label: "审核中", value: "auditing" },
  { label: "已审核", value: "audited" },
]);

// 底部字段
const discount = ref(0.0);
const preReceipt = ref(0.0);

// 结算账户对话框相关
const accountDialogVisible = ref(false);
const selectedAccount = ref("");
const accountSearchKeyword = ref("");
let currentSettlementRow = null;

// 结算方式对话框相关
const methodDialogVisible = ref(false);
const selectedMethod = ref("");
const methodSearchKeyword = ref("");
let currentMethodRow = null;

// 计算属性：合计金额
const settlementTotal = computed(() =>
  settlementTable.value.reduce((sum, item) => sum + item.amount, 0)
);

// 源单表格合计计算
const sourceTotals = computed(() => ({
  totalOrderAmount: sourceTable.value.reduce(
    (sum, item) => sum + item.orderAmount,
    0
  ),
  totalTotalPreReceive: sourceTable.value.reduce(
    (sum, item) => sum + item.totalPreReceive,
    0
  ),
  totalCurrentPreReceive: sourceTable.value.reduce(
    (sum, item) => sum + item.currentPreReceive,
    0
  ),
}));

// 计算属性：搜索过滤
const filteredAccountOptions = computed(() => {
  if (!accountSearchKeyword.value) return settlementAccountOptions.value;
  return settlementAccountOptions.value.filter(
    (item) =>
      item.label.includes(accountSearchKeyword.value) ||
      item.value.includes(accountSearchKeyword.value)
  );
});

const filteredMethodOptions = computed(() => {
  if (!methodSearchKeyword.value) return settlementMethodOptions.value;
  return settlementMethodOptions.value.filter(
    (item) =>
      item.label.includes(methodSearchKeyword.value) ||
      item.value.includes(methodSearchKeyword.value)
  );
});

// 根据值获取标签文本
const getAccountLabel = (value) => {
  const item = settlementAccountOptions.value.find(
    (item) => item.value === value
  );
  return item?.label || "";
};

const getMethodLabel = (value) => {
  const item = settlementMethodOptions.value.find(
    (item) => item.value === value
  );
  return item?.label || "";
};

// 方法：客户弹窗
const fetchCustomers = () => {
  // 模拟接口请求，实际替换为API调用
  customerList.value = [
    {
      category: "华中地区",
      code: "1000000",
      name: "客户1",
      contact: "张",
      phone: "159****1234",
    },
    {
      category: "华北地区",
      code: "1000001",
      name: "客户2",
      contact: "李先生",
      phone: "183****0000",
    },
    {
      category: "华北地区",
      code: "1000002",
      name: "客户3",
      contact: "王",
      phone: "182****1234",
    },
    {
      category: "华南地区",
      code: "1000003",
      name: "客户4-罗",
      contact: "赵",
      phone: "182****1234",
    },
    {
      category: "批发",
      code: "1000004",
      name: "客户5",
      contact: "马路",
      phone: "183****0000",
    },
    {
      category: "广东省内",
      code: "1000005",
      name: "客户6",
      contact: "周",
      phone: "180****0000",
    },
    {
      category: "华中地区",
      code: "1000006",
      name: "客户7",
      contact: "吴",
      phone: "182****1234",
    },
    {
      category: "批发",
      code: "1000007",
      name: "客户8",
      contact: "郑",
      phone: "159****1234",
    },
    {
      category: "华中地区",
      code: "1000008",
      name: "客户9",
      contact: "王",
      phone: "175****1234",
    },
  ];
};
const selectedCustomerRows = ref([]);
const handleCustomerSelection = (val) => {
  selectedCustomerRows.value = val;
};
const confirmCustomer = () => {
  if (selectedCustomerRows.value.length) {
    const customer = selectedCustomerRows.value[0];
    selectedCustomer.value = {
      name: customer.name,
      code: customer.code,
      contact: customer.contact,
      phone: customer.phone,
    };
    totalArrears.value = 1000.0; // 模拟欠款

    // 自动填充源单表格中的客户信息
    if (sourceTable.value.length > 0) {
      sourceTable.value.forEach((row) => {
        row.customer = customer.name;
      });
    }
  }
  customerDialogVisible.value = false;
};

// 方法：业务员
const handleEmployeeChange = (val) => {
  if (val === "add") {
    addEmployeeDialogVisible.value = true;
    selectedEmployee.value = ""; // 重置选择
  } else {
    selectedEmployee.value = val;

    // 自动填充源单表格中的销售人员信息
    if (sourceTable.value.length > 0 && val) {
      const employee = employeeOptions.value.find((item) => item.value === val);
      if (employee) {
        sourceTable.value.forEach((row) => {
          row.seller = employee.label;
        });
      }
    }
  }
};
const saveNewEmployee = () => {
  // 模拟新增职员
  employeeOptions.value.splice(-1, 0, {
    label: newEmployee.name,
    value: newEmployee.name,
  });
  addEmployeeDialogVisible.value = false;
  newEmployee.name = "";
  newEmployee.position = "";
};

// 方法：结算账户对话框
const openAccountDialog = (row) => {
  currentSettlementRow = row;
  selectedAccount.value = row.account;
  accountSearchKeyword.value = ""; // 重置搜索
  accountDialogVisible.value = true;
};

const confirmAccount = () => {
  if (currentSettlementRow) {
    currentSettlementRow.account = selectedAccount.value;
  }
  accountDialogVisible.value = false;
};

// 方法：结算方式对话框
const openMethodDialog = (row) => {
  currentMethodRow = row;
  selectedMethod.value = row.method;
  methodSearchKeyword.value = ""; // 重置搜索
  methodDialogVisible.value = true;
};

const confirmMethod = () => {
  if (currentMethodRow) {
    currentMethodRow.method = selectedMethod.value;
  }
  methodDialogVisible.value = false;
};

// 结算表格操作
const addSettlementRow = () => {
  const newId = settlementTable.value.length + 1;
  settlementTable.value.push({
    id: newId,
    account: "1002", // 默认选中"银行存款"
    amount: 0,
    method: "bank", // 默认选中"银行转账"
    no: "",
    remark: "",
    tradeNo: "",
  });
};
const deleteSettlementRow = (row) => {
  settlementTable.value = settlementTable.value.filter(
    (item) => item.id !== row.id
  );
};

// 源单表格操作
const addSourceRow = () => {
  const newId = sourceTable.value.length + 1;
  sourceTable.value.push({
    id: newId,
    docDate: "",
    sourceNo: "",
    businessType: "",
    seller: selectedEmployee.value
      ? employeeOptions.value.find(
          (item) => item.value === selectedEmployee.value
        )?.label
      : "",
    customer: selectedCustomer.value.name || "",
    orderAmount: 0,
    totalPreReceive: 0,
    currentPreReceive: 0,
    auditStatus: "",
    deliveryDate: "",
    relatedSalesOrder: "",
    relatedPurchaseOrder: "",
    customerAddress: "",
    docRemark: "",
  });
};
const deleteSourceRow = (row) => {
  sourceTable.value = sourceTable.value.filter((item) => item.id !== row.id);
};

// 附件预览（模拟）
const handlePreview = (file) => {
  console.log("预览附件：", file);
};

// 初始化
fetchCustomers();
</script>

<style scoped>
.receipt-container {
  padding: 32px;
  background: #f9fafb;
}

.header-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}

.required::after {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.field-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-section {
  margin-bottom: 24px;
}

.source-actions {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.upload-btn {
  margin-right: 16px;
}

.el-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #f5f7fa;
  --el-table-row-hover-background-color: #f0f2f5;
}

/* 自定义对话框样式 */
.dialog-custom >>> .el-dialog__header {
  padding: 16px 24px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #ebeef5;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.dialog-custom >>> .el-dialog__headerbtn {
  top: 16px;
  right: 24px;
}

.dialog-custom >>> .el-dialog__body {
  padding: 24px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .receipt-container {
    padding: 16px;
  }

  .header-card .flex {
    flex-direction: column;
    gap: 4px;
  }

  .header-card .flex > div {
    min-width: 100%;
  }
}
</style>